package com.study.agp.paging;

import android.util.Log;
import androidx.annotation.NonNull;
import androidx.paging.ItemKeyedDataSource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

public class MovieItemKeyDatasource extends ItemKeyedDataSource<Integer, Movie> {
    private static final String TAG = "MovieItemKeyDatasource";

    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Movie> callback) {
        String paramsStr = String.format(Locale.CHINA,
                "loadInitial -> requestedInitialKey: %d, requestedLoadSize: %d, placeholdersEnabled: %s",
                params.requestedInitialKey, params.requestedLoadSize, params.placeholdersEnabled);
        Log.i(TAG, paramsStr);

        Integer initialKey = params.requestedInitialKey;
        if (initialKey == null) {
            initialKey = 0;
        }

        List<Movie> movieList = new LinkedList<>();
        for (int i = 0, id; i < params.requestedLoadSize; i++) {
            id = initialKey + i;
            movieList.add(new Movie(id, "电影： " + id));
        }
//        callback.onResult(movieList, movieList.size(), 100);
        callback.onResult(movieList);
    }

    @Override
    public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Movie> callback) {
        String paramsStr = String.format(Locale.CHINA,
                "loadAfter -> key: %d, requestedLoadSize: %d",
                params.key, params.requestedLoadSize);
        Log.i(TAG, paramsStr);

        // 表示需要Key之后的数据，不包含Key
        int startKey = params.key + 1;

        if (startKey > params.requestedLoadSize * 10 - 1) {
            callback.onResult(Collections.emptyList());
            return;
        }

        List<Movie> movieList = new LinkedList<>();
        for (int i = 0, id; i < params.requestedLoadSize; i++) {
            id = startKey + i;
            movieList.add(new Movie(id, "电影： " + id));
        }
        callback.onResult(movieList);
    }

    @Override
    public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Movie> callback) {
        String paramsStr = String.format(Locale.CHINA,
                "loadBefore -> key: %d, requestedLoadSize: %d",
                params.key, params.requestedLoadSize);
        Log.i(TAG, paramsStr);
        // ignore：参考MoviePageKeyDataSource
        callback.onResult(Collections.emptyList());
    }

    @NonNull
    @Override
    public Integer getKey(@NonNull Movie item) {
        Log.i(TAG, "getKey: " + item.getId());
        return item.getId();
    }
}
